package appsflyer

import (
	"context"
	"fmt"
	"github.com/go-resty/resty/v2"
	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/logx"
	"navi-mumbai/common/key/appsflyerkey"
	"navi-mumbai/common/key/walletkey"
	"strconv"
	"time"
)

var cli *resty.Client

func InitHttpServer() {
	cli = resty.New()
}

type Event struct {
	logx.Logger
	AppID  string         `json:"app_id"`  // AppsFyler的ID
	DevKey string         `json:"dev_key"` // 校验key
	Body   AppsFlyerEvent `json:"body"`    // 传输数据
}

type AppsFlyerEvent struct {
	AppsflyerID    string `json:"appsflyer_id"`               // 手机设备的AppsflyerID
	AdvertisingID  string `json:"advertising_id,omitempty"`   // 安卓设备ID（可选)
	IDFA           string `json:"idfa,omitempty"`             // IOS（可选)
	CustomerUserId string `json:"customer_user_id,omitempty"` // IOS（可选)
	BundleID       string `json:"bundle_id,omitempty"`        // IOS（可选)
	EventName      string `json:"eventName"`                  // 事件名称
	EventValue     string `json:"eventValue"`                 // 事件值（可选），json string or ''
	EventTime      string `json:"eventTime"`                  // 时间, utc时间
}

type EventInfo struct {
	EventName string `json:"eventName"` // 事件名
	Describe  string `json:"describe"`  // 描述
	Tag       string `json:"tag"`       // tag
}

func GetEventName(moneyAmount int64) *EventInfo {
	// 金币需要除以100, 转化为金币
	moneyAmount = decimal.NewFromInt(moneyAmount).Div(decimal.NewFromInt(walletkey.MoneyScale)).IntPart()
	var eventInfo = &EventInfo{}
	var curMoney int64 = 0
	for i := 0; i < len(appsflyerkey.PurchaseList); i++ {
		if moneyAmount < appsflyerkey.PurchaseList[i] {
			break
		}
		curMoney = appsflyerkey.PurchaseList[i]
	}
	if curMoney == 0 {
		return nil
	}
	eventInfo.EventName = fmt.Sprintf(appsflyerkey.Payment+"%s", strconv.Itoa(int(curMoney)))
	eventInfo.Describe = fmt.Sprintf("用户付费%s成功", strconv.Itoa(int(curMoney)))
	eventInfo.Tag = fmt.Sprintf("af_purchase_%s", strconv.Itoa(int(curMoney)))
	return eventInfo
}

func (e *Event) sendEvent() {
	var rsp *resty.Response
	appsFlyerUrl := fmt.Sprintf(appsflyerkey.AppsFlyerUrlFormat, appsflyerkey.AppID)
	e.Logger.Infof("sendEvent. AppsflyerID: %+v, EventName: %+v, EventValue: %+v, EventTime: %+v", e.Body.AppsflyerID, e.Body.EventName, e.Body.EventValue, e.Body.EventTime)
	rsp, err := cli.R().
		SetHeader("Content-Type", "application/json;charset=UTF-8").
		SetHeader("Accept", "application/json").
		SetHeader("authentication", e.DevKey).
		SetBody(map[string]string{
			"appsflyer_id": e.Body.AppsflyerID,
			"eventName":    e.Body.EventName,
			"eventValue":   e.Body.EventValue,
			"eventTime":    e.Body.EventTime,
		}).Post(appsFlyerUrl)
	e.Logger.Infof("sendEvent. rsp(%v)", rsp)
	if rsp.IsError() {
		e.Logger.Errorf("The appsflyerkey failed to report the event(%v)", err)
		return
	}
	e.Logger.Infof("Successfully reported")
}

// ReportAppsFlyerEvent 上传af事件
func ReportAppsFlyerEvent(ctx context.Context, appsflyerevent string, appsflyerID string, eventValue string) {
	if len(appsflyerID) == 0 {
		// 如果客户端，没传，则写死一个1
		appsflyerID = "1"
	}
	event := &Event{
		Logger: logx.WithContext(ctx),
		DevKey: appsflyerkey.AppsFlyerDevKey,
		AppID:  appsflyerkey.AppID,
		Body: AppsFlyerEvent{
			AppsflyerID: appsflyerID,
			EventName:   appsflyerevent,
			EventValue:  eventValue, // json 字符串
			EventTime:   time.Now().In(time.UTC).Format(time.DateTime),
		},
	}
	event.sendEvent()
}
